package com.jy.oms.framework.asyn.task.queue.filter;

import com.jy.oms.framework.asyn.task.checker.ExecuteTimeRulesConfig;
import com.jy.oms.framework.asyn.task.model.TaskDto;
import com.jy.oms.framework.asyn.task.model.TaskWrapper;
import com.jy.oms.framework.asyn.task.queue.ITaskQueueFilter;
import com.jy.oms.framework.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 如果任务配置在指定时间规则下运行，添加任务时调整延迟执行时间
 *
 * @author liuquan
 */
@Service
public class TaskQueueExecuteTimeRulesFilter implements ITaskQueueFilter {
    @Autowired
    private ExecuteTimeRulesConfig executeTimeRulesConfig;

    @Override
    public void filterOnAdd(TaskWrapper taskWrapper) {
        ExecuteTimeRulesConfig.ExecuteTimeRule taskExecuteTimeRule = executeTimeRulesConfig.getTaskExecuteTimeRule(taskWrapper.getTaskCode());
        if (taskExecuteTimeRule == null) {
            return;
        }

        LocalTime current = LocalTime.now();
        if (taskExecuteTimeRule.getStartTime().isBefore(current) && taskExecuteTimeRule.getEndTime().isAfter(current)) {
            return;
        }

        TaskDto taskDto = taskWrapper.getTaskDto();
        //任务最早时间需要重置为时间规则开始值
        if (taskExecuteTimeRule.getStartTime().isAfter(current)) {
            LocalDateTime earliest = LocalDateTime.of(LocalDate.now(), taskExecuteTimeRule.getStartTime());
            taskDto.setDelayedSeconds(DateUtils.toSeconds(earliest) - DateUtils.toSeconds(LocalDateTime.now()));
        }

        //任务最早时间需要设置为第二天时间规则开始值
        if (taskExecuteTimeRule.getEndTime().isBefore(current)) {
            LocalDateTime earliest = LocalDateTime.of(LocalDate.now(), taskExecuteTimeRule.getStartTime());
            taskDto.setDelayedSeconds(DateUtils.toSeconds(earliest.plusDays(1)) - DateUtils.toSeconds(LocalDateTime.now()));
        }
    }

}
